import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as https from 'https';

interface RunWorkflowParams {
  subject: string;
  total?: number;
  min?: number;
  max?: number;
}

@Injectable()
export class WorkflowService {
  constructor(private readonly configService: ConfigService) {}

  async runWorkflow(params: RunWorkflowParams): Promise<any> {
    console.log('🔧 ENV CHECK -> COZE_TOKEN:', process.env.COZE_TOKEN || '(none)');
    const token = this.configService.get<string>('COZE_TOKEN') || process.env.COZE_TOKEN;
    const workflowId = this.configService.get<string>('COZE_WORKFLOW_ADD_ID') || process.env.COZE_WORKFLOW_ADD_ID || '7566577660957950015';

    // Debug logs: mask sensitive value
    const masked = token ? `${token.slice(0, 6)}...${token.slice(-4)}` : undefined;
    // eslint-disable-next-line no-console
    console.log('[WorkflowService] COZE_TOKEN present:', Boolean(token), masked ? `(masked: ${masked})` : '');
    // eslint-disable-next-line no-console

    if (!token) {
      throw new Error('Server missing COZE_TOKEN configuration');
    }

    const payload = {
      workflow_id: workflowId,
      parameters: {
        subject: params.subject,
        total: Number.isFinite(params.total as number) ? Number(params.total) : 1,
        ...(Number.isFinite(params.min as number) && (params.min as number) >= 0 ? { min: Number(params.min) } : {}),
        ...(Number.isFinite(params.max as number) && (params.max as number) >= 0 ? { max: Number(params.max) } : {}),
      },
    };

    const body = JSON.stringify(payload);

    const options: https.RequestOptions = {
      method: 'POST',
      hostname: 'api.coze.cn',
      path: '/v1/workflow/run',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        'Content-Length': Buffer.byteLength(body),
      },
    };

    const responseText: string = await new Promise((resolve, reject) => {
      const req = https.request(options, (res) => {
        const chunks: Buffer[] = [];
        res.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
        res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
      });
      req.on('error', reject);
      req.write(body);
      req.end();
    });

    // Try to parse JSON; if parsing fails, return raw text
    let data: any;
    try {
      data = JSON.parse(responseText);
    } catch {
      data = responseText;
    }

    // Try to parse nested data field if it is a JSON string
    try {
      if (data && typeof data.data === 'string') {
        data = { ...data, data: JSON.parse(data.data) };
      }
    } catch {
      // ignore nested parse errors
    }

    return data;
  }

  async runWorkflowWithEnvId(params: RunWorkflowParams, envKey: string): Promise<any> {
    const token = this.configService.get<string>('COZE_TOKEN') || process.env.COZE_TOKEN;
    const workflowId = this.configService.get<string>(envKey) || (process.env as any)[envKey];

    const masked = token ? `${token.slice(0, 6)}...${token.slice(-4)}` : undefined;
    // eslint-disable-next-line no-console
    console.log(`[WorkflowService] ${envKey}:`, workflowId || '(none)');
    // eslint-disable-next-line no-console
    console.log('[WorkflowService] COZE_TOKEN present:', Boolean(token), masked ? `(masked: ${masked})` : '');

    if (!token) {
      throw new Error('Server missing COZE_TOKEN configuration');
    }
    if (!workflowId) {
      throw new Error(`Missing ${envKey} configuration`);
    }

    const payload = {
      workflow_id: workflowId,
      parameters: {
        subject: params.subject,
        total: Number.isFinite(params.total as number) ? Number(params.total) : 1,
        ...(Number.isFinite(params.min as number) && (params.min as number) >= 0 ? { min: Number(params.min) } : {}),
        ...(Number.isFinite(params.max as number) && (params.max as number) >= 0 ? { max: Number(params.max) } : {}),
      },
    };

    // eslint-disable-next-line no-console
    console.log('[WorkflowService] Sending payload:', JSON.stringify(payload, null, 2));

    const body = JSON.stringify(payload);

    const options: https.RequestOptions = {
      method: 'POST',
      hostname: 'api.coze.cn',
      path: '/v1/workflow/run',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        'Content-Length': Buffer.byteLength(body),
      },
    };

    const responseText: string = await new Promise((resolve, reject) => {
      const req = https.request(options, (res) => {
        const chunks: Buffer[] = [];
        res.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
        res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
      });
      req.on('error', reject);
      req.write(body);
      req.end();
    });

    let data: any;
    try {
      data = JSON.parse(responseText);
    } catch {
      data = responseText;
    }
    try {
      if (data && typeof data.data === 'string') {
        data = { ...data, data: JSON.parse(data.data) };
      }
    } catch {}

    // eslint-disable-next-line no-console
    console.log('[WorkflowService] Response:', JSON.stringify(data, null, 2));

    return data;
  }

  async runWorkflowWithCustomParams(params: any, envKey: string): Promise<any> {
    const token = this.configService.get<string>('COZE_TOKEN') || process.env.COZE_TOKEN;
    const workflowId = this.configService.get<string>(envKey) || (process.env as any)[envKey];

    const masked = token ? `${token.slice(0, 6)}...${token.slice(-4)}` : undefined;
    // eslint-disable-next-line no-console
    console.log(`[WorkflowService] ${envKey}:`, workflowId || '(none)');
    // eslint-disable-next-line no-console
    console.log('[WorkflowService] COZE_TOKEN present:', Boolean(token), masked ? `(masked: ${masked})` : '');

    if (!token) {
      throw new Error('Server missing COZE_TOKEN configuration');
    }
    if (!workflowId) {
      throw new Error(`Missing ${envKey} configuration`);
    }

    // 直接传递所有参数，不做特殊处理
    const payload = {
      workflow_id: workflowId,
      parameters: params,
    };

    // eslint-disable-next-line no-console
    console.log('[WorkflowService] Sending payload:', JSON.stringify(payload, null, 2));

    const body = JSON.stringify(payload);

    const options: https.RequestOptions = {
      method: 'POST',
      hostname: 'api.coze.cn',
      path: '/v1/workflow/run',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        'Content-Length': Buffer.byteLength(body),
      },
    };

    const responseText: string = await new Promise((resolve, reject) => {
      const req = https.request(options, (res) => {
        const chunks: Buffer[] = [];
        res.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
        res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
      });
      req.on('error', reject);
      req.write(body);
      req.end();
    });

    let data: any;
    try {
      data = JSON.parse(responseText);
    } catch {
      data = responseText;
    }
    try {
      if (data && typeof data.data === 'string') {
        data = { ...data, data: JSON.parse(data.data) };
      }
    } catch {}

    // eslint-disable-next-line no-console
    console.log('[WorkflowService] Response:', JSON.stringify(data, null, 2));

    return data;
  }
}


